package com.openbrew.openbrewpos;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class RESTfulConnect {
	public static String postResource(final String dbName, final String USER, final String PASS, final String json) throws IOException{
		try{
			SSLContext sc = SSLContext.getInstance("TLS");
			TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
			    public X509Certificate[] getAcceptedIssuers() {
			        return null;
			    }
			    @Override
			    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			        return;
			    }
			    @Override
			    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			        return;
			    }
			} };
			sc.init(null, trustAllCerts, new SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
			
			HostnameVerifier hv = new HostnameVerifier(){
			    public boolean verify(String urlHostName, SSLSession session){
			        System.out.println("Warning: URL Host: " + urlHostName + " vs. "
			                + session.getPeerHost());
			        return true;
			    }
			};
			    
			Authenticator.setDefault(new Authenticator() {
		        protected PasswordAuthentication getPasswordAuthentication() {
		          return new PasswordAuthentication(USER, PASS.toCharArray());
		        }
		    });
			// Tell the URLConnection to use a SocketFactory from our SSLContext
			URL url = new URL(dbName);
			HttpsURLConnection urlConnection =
			    (HttpsURLConnection)url.openConnection();
			urlConnection.setHostnameVerifier(hv);
			urlConnection.setRequestMethod("POST");
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.setUseCaches(false);
			urlConnection.setAllowUserInteraction(false);
			urlConnection.setRequestProperty("Content-Type", "application/json");
			
			OutputStream out = urlConnection.getOutputStream();
			try{
				OutputStreamWriter wr = new OutputStreamWriter(out);
				wr.write(json);
				wr.flush();
				wr.close();
			} catch(IOException e){
				e.printStackTrace();
			} finally {
				if(out != null){
					out.close();
				}
			}
			
			InputStream in = urlConnection.getInputStream();
			return convertStreamToString(in);
		}catch(Exception ex){
			ex.printStackTrace();
			return "DIDNT WORK";
		}
	}
	
	public static String putResource(final String dbName, final String USER, final String PASS, final String json) throws IOException{
		try{
			SSLContext sc = SSLContext.getInstance("TLS");
			TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
			    public X509Certificate[] getAcceptedIssuers() {
			        return null;
			    }
			    @Override
			    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			        return;
			    }
			    @Override
			    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			        return;
			    }
			} };
			sc.init(null, trustAllCerts, new SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
			
			HostnameVerifier hv = new HostnameVerifier(){
			    public boolean verify(String urlHostName, SSLSession session){
			        System.out.println("Warning: URL Host: " + urlHostName + " vs. "
			                + session.getPeerHost());
			        return true;
			    }
			};
			    
			Authenticator.setDefault(new Authenticator() {
		        protected PasswordAuthentication getPasswordAuthentication() {
		          return new PasswordAuthentication(USER, PASS.toCharArray());
		        }
		    });
			// Tell the URLConnection to use a SocketFactory from our SSLContext
			URL url = new URL(dbName);
			HttpsURLConnection urlConnection =
			    (HttpsURLConnection)url.openConnection();
			urlConnection.setHostnameVerifier(hv);
			urlConnection.setRequestMethod("PUT");
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.setUseCaches(false);
			urlConnection.setAllowUserInteraction(false);
			urlConnection.setRequestProperty("Content-Type", "application/json");
			
			OutputStream out = urlConnection.getOutputStream();
			try{
				OutputStreamWriter wr = new OutputStreamWriter(out);
				wr.write(json);
				wr.flush();
				wr.close();
			} catch(IOException e){
				e.printStackTrace();
			} finally {
				if(out != null){
					out.close();
				}
			}
			
			InputStream in = urlConnection.getInputStream();
			return convertStreamToString(in);
		}catch(Exception ex){
			ex.printStackTrace();
			return "DIDNT WORK";
		}
	}
	
    public static String getResource(final String dbName, final String USER, final String PASS) throws IOException{
		try{
			SSLContext sc = SSLContext.getInstance("TLS");
			TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
			    public X509Certificate[] getAcceptedIssuers() {
			        return null;
			    }
			    @Override
			    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			        return;
			}
			    @Override
			    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			        return;
			    }
			} };
			sc.init(null, trustAllCerts, new SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
			
			HostnameVerifier hv = new HostnameVerifier(){
			    public boolean verify(String urlHostName, SSLSession session){
			        System.out.println("Warning: URL Host: " + urlHostName + " vs. "
			                + session.getPeerHost());
			        return true;
			    }
			};
			    
			Authenticator.setDefault(new Authenticator() {
		        protected PasswordAuthentication getPasswordAuthentication() {
		          return new PasswordAuthentication(USER, PASS.toCharArray());
		        }
		    });
			// Tell the URLConnection to use a SocketFactory from our SSLContext
			URL url = new URL(dbName);
			HttpsURLConnection urlConnection =
			    (HttpsURLConnection)url.openConnection();
			urlConnection.setHostnameVerifier(hv);
			urlConnection.setRequestMethod("GET");
			InputStream in = urlConnection.getInputStream();
			return convertStreamToString(in);
		}catch(Exception ex){
			ex.printStackTrace();
			return "DIDNT WORK";
		}
    }
	
	public static String deleteResource(final String dbName, final String USER, final String PASS, final String id) throws IOException{
		try{
			SSLContext sc = SSLContext.getInstance("TLS");
			TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
			    public X509Certificate[] getAcceptedIssuers() {
			        return null;
			    }
			    @Override
			    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			        return;
			    }
			    @Override
			    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			        return;
			    }
			} };
			sc.init(null, trustAllCerts, new SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
			
			HostnameVerifier hv = new HostnameVerifier(){
			    public boolean verify(String urlHostName, SSLSession session){
			        System.out.println("Warning: URL Host: " + urlHostName + " vs. "
			                + session.getPeerHost());
			        return true;
			    }
			};
			    
			Authenticator.setDefault(new Authenticator() {
		        protected PasswordAuthentication getPasswordAuthentication() {
		          return new PasswordAuthentication(USER, PASS.toCharArray());
		        }
		    });
			// Tell the URLConnection to use a SocketFactory from our SSLContext
			URL url = new URL(dbName+"/"+id);
			HttpsURLConnection urlConnection =
			    (HttpsURLConnection)url.openConnection();
			urlConnection.setHostnameVerifier(hv);
			urlConnection.setRequestMethod("DELETE");
			InputStream in = urlConnection.getInputStream();
			return convertStreamToString(in);
		}catch(Exception ex){
			ex.printStackTrace();
			return "DIDNT WORK";
		}
	}
	
	private static String convertStreamToString(InputStream is) {
	    ByteArrayOutputStream oas = new ByteArrayOutputStream();
	    copyStream(is, oas);
	    String t = oas.toString();
	    try {
	        oas.close();
	        oas = null;
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    return t;
	}

	private static void copyStream(InputStream is, OutputStream os)
	{
	    final int buffer_size = 1024;
	    try
	    {
	        byte[] bytes=new byte[buffer_size];
	        for(;;)
	        {
	          int count=is.read(bytes, 0, buffer_size);
	          if(count==-1)
	              break;
	          os.write(bytes, 0, count);
	        }
	    }
	    catch(Exception ex){}
	}
    
}
